package nl.maarten.docenthelp.entity.thread;

import nl.maarten.docenthelp.entity.Session;
import nl.maarten.docenthelp.manager.SessionManager;

public class AliveThread extends Thread 
{
	private SessionManager sessionManager = SessionManager.getInstance();
	
	private boolean running = false;
	
	@Override
	public void run()
	{
		running = true;
		
		while( running )
		{
			for( Session session : sessionManager.getSessions().values() )
			{
				try
				{
					//TODO: fix this thread. when client closed connection the session is still there!
					String line = session.getIn().readLine();
					System.out.println( session.getID() + " says: " + line );
				}
				catch( Exception e )
				{
					System.out.println( "Session #" + session.getID() + " closed!" );
					sessionManager.getClosedSessions().put(session.getID(), session);
					return;
				}
			}
			
			sessionManager.syncSessions();
		}
	}
	
	public void close()
	{
		running = false;
		
		try
		{
			this.join();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
